//
//  ActionView.m
//  SlashEM
//
//  Created by dirk on 1/14/10.
//  Copyright 2010 Dirk Zimmermann. All rights reserved.
//

//  This file is part of Slash'EM.
//
//  Slash'EM is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, version 2 of the License only.
//
//  Slash'EM is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with Slash'EM.  If not, see <http://www.gnu.org/licenses/>.

#import "ActionView.h"
#import "Action.h"
#import "ZAction.h"
#import "NhEventQueue.h"
#import "ActionBar.h"

@implementation ActionView

@synthesize actions;

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
		self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
		myTableView = [[UITableView alloc] initWithFrame:self.contentView.bounds style:UITableViewStyleGrouped];
		myTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
		myTableView.dataSource = self;
		myTableView.delegate = self;
		myTableView.backgroundColor = [UIColor clearColor];
		[self.contentView addSubview:myTableView];
		[myTableView release];
    }
    return self;
}

// awkward and slow, but seems to be the only way to resize cells on rotation
- (void)layoutSubviews {
	[super layoutSubviews];
	[myTableView reloadData];
}

- (void)dealloc {
    [super dealloc];
}

#pragma mark UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return actions.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	static NSString *cellId = @"actionViewControllerCellId";
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
	if (!cell) {
		cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellId] autorelease];
		cell.autoresizingMask = UIViewAutoresizingFlexibleWidth;
	}
	//int section = [indexPath section];
	int row = [indexPath row];
	id<Action> action = [actions objectAtIndex:row];
	cell.text = action.title;
	return cell;
}

#pragma mark UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	//int section = [indexPath section];
	int row = [indexPath row];
	id<Action> action = [actions objectAtIndex:row];
	[action invoke:self];
	[self removeFromSuperview];
}

@end
